package org.study.atomikos.mybatisplus.boot.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.study.atomikos.mybatisplus.boot.mapper.primary.Ds1UserMapper;
import org.study.atomikos.mybatisplus.boot.mapper.secondary.Ds2UserMapper;
import org.study.atomikos.mybatisplus.boot.model.primary.Ds1User;
import org.study.atomikos.mybatisplus.boot.model.secondary.Ds2User;

/**
 * 创建一个 Service 实现，模拟两种不同的情况。
 * 这里 tx 函数，是两句 update 操作，一般都会成功；
 * 而 tx2 函数中，我们人为的制造了一个异常，这个异常是在 test1 库中的数据更新后才产生的，这样就可以测试一下 test1 更新成功，之后是否还能在 JTA 的帮助下实现回滚。
 *
 * @author Administrator
 * @date 2021-11-29
 */
@Service
public class TestService {
    @Autowired
    private Ds1UserMapper ds1UserMapper;
    @Autowired
    private Ds1UserService ds1UserService;
    @Autowired
    private Ds2UserMapper ds2UserMapper;
    @Autowired
    private Ds2UserService ds2UserService;

    @Transactional(rollbackFor = Exception.class)
    public void txCommit() {
        Ds1User ds1User = new Ds1User();
        ds1User.setAge(20);
        QueryWrapper<Ds1User> ds1UserQueryWrapper = new QueryWrapper<>();
        ds1UserQueryWrapper.eq("name", "admin");
        ds1UserMapper.update(ds1User, ds1UserQueryWrapper);

        Ds2User ds2User = new Ds2User();
        ds2User.setAge(30);
        QueryWrapper<Ds2User> ds2UserQueryWrapper = new QueryWrapper<>();
        ds2UserQueryWrapper.eq("name", "test");
        ds2UserMapper.update(ds2User, ds2UserQueryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    public void txRollback() {
        Ds1User ds1User = new Ds1User();
        ds1User.setAge(20);
        QueryWrapper<Ds1User> ds1UserQueryWrapper = new QueryWrapper<>();
        ds1UserQueryWrapper.eq("name", "admin");
        ds1UserMapper.update(ds1User, ds1UserQueryWrapper);

        Ds2User ds2User = new Ds2User();
        ds2User.setAge(30);
        QueryWrapper<Ds2User> ds2UserQueryWrapper = new QueryWrapper<>();
        ds2UserQueryWrapper.eq("name", "test");
        ds2UserMapper.update(ds2User, ds2UserQueryWrapper);

        // 模拟异常
        throw new RuntimeException();
    }
}
